import React, {Component} from 'react';
import {Table, Button, Form, Input, Icon, Row, InputNumber, Col, Layout, message, Modal,} from 'antd';
import app from "../app";
import {config} from "../config";
import {requestUrl,type} from "../value";
import {PictureUpload} from "../components/pictureUpload";
import '../css/shopGoods.css';

const FormItem = Form.Item;
const confirm = Modal.confirm;
const {Content} = Layout;

const urlItem=type.ADD_TYPE;
const DEL_TYPE=type.DEL_TYPE;

class TypeManage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            ShopGoodsList: [
                {
                    data: [],
                    level: 1,
                    name: '添加一级分类'
                },
                {
                    data: [],
                    level: 2,
                    name: '添加二级分类'
                }
            ],
            visible: false,
            file: [],
            fileList: [],
            addConfirmLoading: false,
            selectTypeList: [
                {type_id: ''},
                {type_id: ''},
                {type_id: ''},
            ],
            imageVisible: false,
            occurImage: '',  //放大的图片
            pictureList:[],
            pictureList1:[],

        };
    }

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 15},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        const {pictureUpload,pictureUpload1}=this.state;
        return (
            <span>
                <GoodsSet
                    visible={this.state.visible}
                    title={'添加分类'} buttonText={'添加分类'}
                    width={'400px'}
                    addConfirmLoading={this.state.addConfirmLoading}
                    clickOk={(e) => this.handleSubmit(e)}
                    clickCancel={(e) => this.handleCancel(e)}
                >
                    <Row>

                        <Col offset={3} span={16}>
                            <div>
                                <Form className="login-form">
                                    <FormItem label={'分类名'} {...this.formItemLayout}>
                                        {getFieldDecorator('type_name', {
                                            rules: [{required: true, message: '请输入分类名!'}],
                                        })(
                                            <Input
                                                prefix={<Icon type="switcher" style={{fontSize: 13}}/>}
                                                placeholder="输入分类名"/>
                                        )}
                                    </FormItem>
                                      <FormItem label={'图片'} required={true}  {...this.formItemLayout}>
                                        {getFieldDecorator('myFile')(
                                            <PictureUpload
                                                pictureList={this.state.pictureList} len={1}
                                                pictureList1={this.state.pictureList1}
                                                getPictureList={(data, data1) => this.handleGetIntelligenceList(data, data1)}

                                            />
                                        )}
                                    </FormItem>
                                      <FormItem label={'编号'} required={true}  {...this.formItemLayout}>
                                           {getFieldDecorator('type_sequence', {
                                               rules: [{required: true, message: '请输入编号!'}],
                                           })(
                                               <InputNumber min={0} style={{width: '100%'}} precision={0}/>
                                           )}
                                    </FormItem>
                                </Form>
                            </div>
                        </Col>
                    </Row>
                </GoodsSet>
                <Row>
                     <Modal
                         visible={this.state.imageVisible}
                         width={"600px"}
                         wrapClassName="vertical-center-modal"
                         onCancel={() => {
                             this.setImageModal(false)
                         }}
                         footer={[
                             <Button key="back" size="large" onClick={() => {
                                 this.setImageModal(false)
                             }}>取消</Button>,
                         ]}
                     >
                        <Row>
                            <Col>
                                <img height={'500px'} width={"500px"} style={{marginRight: '5px'}}
                                     src={app.imgServerUrl + this.state.occurImage}
                                     alt=""/>
                            </Col>
                        </Row>
                    </Modal>
                    {this.state.ShopGoodsList.map((item, index) => {
                        return (
                            <Col span={8} key={index}>
                                <Layout style={{
                                    borderRadius: 8,
                                    minHeight: 600,
                                    maxWidth: 400,
                                    border: '1px solid #ddd'
                                }}>
                                    <Button type="primary"
                                            onClick={(isOpen, type) => this.OnclickOpen(true, Number(item.level))}>{item.name}</Button>
                                    < Content className="addType" style={{
                                        background: '#fff',
                                        margin: 0,
                                        minHeight: 600,
                                        maxWidth: 400,
                                        maxHeight: 640,
                                        overflowY: 'scroll'
                                    }}>
                                        <table className="m-winRecord" style={{
                                            width: '100%',
                                            marginTop: '15px',
                                            borderCollapse: 'collapse',

                                        }}>
                                            <thead>
                                            </thead>
                                            <tbody>
                                            {item.data.length === 0 ?
                                                <tr>
                                                    <td>无分类</td>
                                                </tr> : item.data.map((GoodsItem, GoodsIndex) => {
                                                    return (
                                                        <tr key={GoodsIndex}
                                                            onClick={(e) => this.seacrhSecond(Number(item.level), GoodsItem.type_id)} //查找当前点击的分类的下级
                                                            className={GoodsItem.type_id === this.state.selectTypeList[index].type_id ? 'selectType' : ''}>
                                                            <td className='editIcon'
                                                                style={{padding: '8px 0px 8px 3px'}}>{GoodsItem.type_name}</td>
                                                            <td style={{marginRight: '15px'}}>{GoodsItem.type_sequence}</td>
                                                            <td><img onClick={(pathNames) => {
                                                                this.setImageModal(true, GoodsItem.file_path)
                                                            }} width={30} height={30}
                                                                     src={app.imgServerUrl + GoodsItem.file_path}
                                                                     alt=""/></td>
                                                            <td className='editIcon'
                                                                style={{padding: '8px 0px 8px 3px'}}>
                                                                {this.UpdateSet(GoodsItem, Number(item.level), GoodsIndex)}
                                                            </td>
                                                        </tr>
                                                    )
                                                })}
                                            </tbody>
                                        </table>
                                    </Content>
                                </Layout>
                            </Col>
                        )
                    })}
                </Row>
            </span>
        )
    }


    componentDidMount() {
        //查询一级分类
        message.config({
            top: '30%',
            duration: 2,
        });
        this.SearchGoods(1, null);  //搜索分类
    }

    // 放大图片
    setImageModal(visible, pathname) {
        this.setState({
            imageVisible: visible,
            occurImage: pathname
        })
    }


    // 修改 停用删除页面
    UpdateSet(value, type, index) {
        let isable;
        let text;
        let typeColor;
        if (value.type_isable == 1) {
            isable = '0';
            text = '停用';
            typeColor = 'danger'
        } else {
            isable = '1';
            text = '恢复';
            typeColor = 'primary'
        }
        return (
            <span>
                 <TypeEdits
                     clickOk={(value) => {
                         this.handleChildSubmit(value)
                     }}
                     myFileList={[{
                         name: value.file_name,
                         url: config.imgServerUrl + value.file_path,
                         uid: value.type_id,
                         deliverUrl: value.file_path
                     }]}
                     data={value}
                     type="edit"
                     title={'修改分类'} buttonText={'修改'} width={'400px'}/>

                <Button className='btnRight' type={typeColor}
                        onClick={(e) => this.handleReturn(e, type, {
                            type_id: value.type_id,
                            type_isable: isable,
                            type_level: value.type_level,
                            type_parentId: value.type_parentId
                        }, isable)}>{text}</Button>
                <Button type='danger' onClick={(e) => this.handleDeleteType(e, {
                    type_id: value.type_id,
                    type_name: value.type_name,
                    type_parentId: value.type_parentId
                }, type)}>删除</Button>
            </span>
        )

    }

    /**
     * 子组件成功修改后在此刷新页面
     * @param formData
     */
    handleChildSubmit(formData) {
        this.SearchGoods(Number(formData.type_level), formData.type_parentId);  //搜索分类
    }

    /**
     * 删除分类
     * @param e
     * @param data
     * @param type
     */
    handleDeleteType(e, data, type) {
        let that = this;
        confirm(
            {
                content: '删除后不能恢复,请问是否删除',
                onOk() {
                    app.post(DEL_TYPE, {
                        type_id: data.type_id,
                        type_name: data.type_name,
                        log_type: 0
                    }).then(req => {
                        if (req.code == 1) {
                           app.alert(req.msg,'success',3);
                            that.SearchGoods(type, data.type_parentId);  //刷新二级的数据

                        }  else if(req.code==2){
                            app.alert(req.msg, 'error', '3');
                        }
                    })
                },
                onCancel() {
                },
            });
    }


    /***
     * 点击表格的某一行 查找下级分类  type_id为父类id
     */
    seacrhSecond(level, type_id, e) {
        let selectTypeList = this.state.selectTypeList;
        switch (level) {
            case 1:
                selectTypeList[0].type_id = '';
                selectTypeList[1].type_id = '';
                selectTypeList[2].type_id = '';
                break;
            case 2:
                selectTypeList[1].type_id = '';
                selectTypeList[2].type_id = '';
                break;
            case 3:
                selectTypeList[2].type_id = '';
                break;
        }
        selectTypeList[level - 1].type_id = type_id;
        this.setState({selectTypeList});
        this.SearchGoods(level + 1, type_id);
    }

    /***
     * 请求查询分类  level表示分类等级1,2,3,  type_id为父类id
     */
    SearchGoods(level, type_id) {
        let data = {};
        let ShopGoodsList = this.state.ShopGoodsList;  //所有分类，包含一级 二级 三级等
        let selectTypeList = this.state.selectTypeList;  //当前选中的分类id，selectTypeList[0]为一级id，selectTypeList[1]为二级id,以此类推
        // 一级分类
        if (level === 1) {

        } else {
            data = {type_parentId: type_id}
        }
        app.post(type.SEARCH_TYPE_LIST, data).then(req => {
            if (req.code == 1) {
                //把查找的分类存储到该等级的分类
                ShopGoodsList[level - 1].data = req.data;   //level级分类的数据

                // 只有初始化时默认显示二级分类的第一个分类
                if (selectTypeList[level - 1].type_id == '') {
                    selectTypeList[level - 1].type_id = req.data[0].type_id;
                }
                this.setState({ShopGoodsList, selectTypeList});
                //如果当前等级是最后一级就停止查询
                if (level === 3) {

                }
                //查询当前分类里第一个的所有下级分类
                else {
                    // 初始化时默认显示第一个分类
                    if (selectTypeList[level - 1].type_id == '') {
                        this.SearchGoods(level + 1, req.data[0].type_id);
                    }
                    else {
                        this.SearchGoods(level + 1, selectTypeList[level - 1].type_id);
                    }

                }
            } else if (req.code == 2) {

                if (level < 4) {  //这个判断防止点击二级分类的某行时出错
                    // 一级没有数据
                    if (level == 1) {
                        ShopGoodsList[level - 1].data = [];
                        selectTypeList[level - 1].type_id = '';
                    }

                    // 二级没有数据时
                    if (level == 2) {
                        ShopGoodsList[level - 1].data = [];
                        selectTypeList[level - 1].type_id = '';

                        ShopGoodsList[level].data = [];  //当二级数据为空时清空三级的数据
                        selectTypeList[level].type_id = ''; //当二级数据为空时清空三级的数据

                    }

                    this.setState({ShopGoodsList, selectTypeList});
                }
            }
        })
    }

    //启用停用分类
    handleReturn(e, level, value, isable) {
        e.stopPropagation();
        let text = '';
        if (isable == '0') {
            text = '停用成功'
        }
        if (isable == '1') {
            text = '启用成功'
        }
        let selectTypeList = this.state.selectTypeList;
        this.setState({loading: true});
        app.post(type.UPDATE_TYPE_ISABLE, value).then(req => {
            this.setState({loading: false});
            if (req.code == 1) {
                app.alert(text, 'success', 3);
                let ShopGoodsList = this.state.ShopGoodsList;
                selectTypeList[level - 1].type_id = value.type_id;
                this.setState({ShopGoodsList, selectTypeList});
                // this.SearchGoods(level, value.type_id);
                this.SearchGoods(level, value.type_parentId);
            }  else if(req.code==2){
                app.alert(req.msg, 'error', '3');
            }
        })
    }

    //选择图片
    GetFileWall(file, fileList) {
        this.setState({fileList: fileList, file: file});
    }

    //打开等级分类添加框
    OnclickOpen(isOpen, type) {
        this.setState({visible: isOpen, level: type});
    }

    handleCancel(visible) {
        if (!visible) {
            this.props.form.resetFields();
            this.setState({
                fileList: [],
                file: [],
                visible: visible
            })
        }
    }

    //添加分类
    handleSubmit = (e) => {
        const type = this.state.level;  //弹出添加框的时候保存的当前等级
        let file = this.state.pictureList1;
        let selectTypeList = this.state.selectTypeList;  //当前点击的分类id，用来查找下级分类
        this.props.form.validateFields((err, values) => {
            if (!err) {
                if (file) {
                    file.forEach((item) => {
                        values.file_path = item.file_path;
                        values.file_name = item.file_name;
                    })
                }
                values.type_level = type;

                // 二级以上的分类
                if (type > 1) {
                    values.type_parentId = selectTypeList[type - 2].type_id;
                }
                if (values.file_name) {
                    this.setState({
                        addConfirmLoading: true,
                        loading: true
                    });

                    console.log(values);
                    values.type_sequence = values.type_sequence + '';
                    app.post(urlItem, values).then(req => {
                        this.setState({
                            addConfirmLoading: false
                        });
                        if (req.code == 1) {
                            this.setState({loading: false, visible: false, file: [], fileList: []});
                            this.props.form.resetFields();
                            this.SearchGoods(type, values.type_parentId);
                            app.alert('添加成功', 'info', 3);
                        } else {
                            this.setState({loading: false});
                            app.alert(req.msg, 'error', 3);
                        }
                    })
                }

                else {
                    message.info('请上传图片');
                }
            }
        });
    };

    /**
     * 获取店铺资质图片
     * @param intelligence
     * @param intelligence1
     */
    handleGetIntelligenceList(pictureList, pictureList1) {
        this.setState({pictureList, pictureList1});
    }
}

// 分类的添加弹出框
class GoodsSet extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    }

    handleCancel(isOpen) {
        //关闭分类详情
        this.props.clickCancel();
    }

    render() {
        return (
            <span>
                <Modal
                    confirmLoading={this.props.addConfirmLoading}
                    maskClosable={false}
                    title={this.props.title}
                    wrapClassName="vertical-center-modal"
                    width={this.props.width}
                    onOk={(e, id, type) => this.props.clickOk(e, id, type)}
                    visible={this.props.visible}
                    onCancel={(ipOpen) => this.handleCancel(false)}
                >
                    {this.props.children}
                </Modal>
            </span>
        );
    }

    componentWillReceiveProps(props) {
        this.setState({visible: props.visible, addConfirmLoading: props.addConfirmLoading});
    }
}


// 修改分类
class TypeEdit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            modal2Visible: false,
            editConfirmLoading: false,
            fileList: [],  //获取上传的图片信息并在编辑的时候把上传的图片传给编辑框中:
            file: [],  //传给服务器的图片参数
            pictureList:[],
            pictureList1:[],
        };
    }

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    }

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <span style={{paddingLeft: 10, paddingRight: 10}}>
                <Button type="primary" onClick={() => this.setModal2Visible(true)}>{this.props.buttonText}</Button>
                <Modal
                    title={this.props.title}
                    wrapClassName="vertical-center-modal"
                    width={this.props.width}
                    visible={this.state.modal2Visible}
                    data={this.props.data}
                    confirmLoading={this.state.editConfirmLoading}
                    onOk={(e) => this.handleEditSubmit(e)}
                    onCancel={() => this.setModal2Visible(false)}
                >
                     <Row>
                        <Col offset={3} span={16}>
                            <div>
                                <Form className="login-form">
                                    <FormItem label={'分类名'} {...this.formItemLayout} >
                                        {getFieldDecorator('type_name', {
                                            rules: [{required: true, message: '请输入分类名!'}],
                                        })(
                                            <Input
                                                prefix={<Icon type="switcher" style={{fontSize: 13}}/>}
                                                placeholder="输入分类名"/>
                                        )}
                                    </FormItem>
                                      <FormItem label={'图片'} {...this.formItemLayout}>
                                        {getFieldDecorator('myFile')(
                                            <PictureUpload
                                                pictureList={this.state.pictureList} len={1}
                                                pictureList1={this.state.pictureList1}
                                                getPictureList={(data, data1) => this.handleGetIntelligenceList(data, data1)}
                                            />
                                        )}
                                    </FormItem>
                                     <FormItem label={'序号'} required={true}  {...this.formItemLayout}>
                                           {getFieldDecorator('type_sequence', {
                                               rules: [{required: true, message: '请输入序号!'}],
                                           })(
                                               <InputNumber style={{width: '100%'}} precision={0}/>
                                           )}
                                    </FormItem>
                                </Form>
                            </div>
                        </Col>
                    </Row>
                </Modal>
            </span>
        );
    }

    componentDidMount() {

    }

    // 获取上传的图片的相关信息
    handleGetPictureWall(file, fileList) {
        this.setState({
            fileList: fileList,
            file: file
        })
    }

    handleEditSubmit(e) {
        let formData = this.props.data;
        let file = this.state.pictureList1;
        let oldName = formData.type_name;
        if (this.state.pictureList1.length != 0) {
            console.log(this.state.file);
            this.props.form.validateFields((err, values) => {
                if (!err) {
                    if (file) {
                        file.forEach((item) => {
                            // 如果没有改过图片，则使用以前的照片
                            if (item.deliverUrl) {
                                formData.file_path = item.deliverUrl;
                                formData.file_name = item.name;
                            }
                            else {
                                formData.file_path = item.file_path;
                                formData.file_name = item.file_name;
                            }
                        })
                    }

                    // 如果没有修改名字
                    if (oldName == values.type_name) {
                        formData.old_name = values.type_name; //修改前的分类名字
                        formData.type_name = values.type_name;//新的分类名字
                        formData.isUpdateName = '0'; //是否修改了分类名字(0,不是 1,是)
                    } else {
                        formData.old_name = oldName; //修改前的分类名字
                        formData.type_name = values.type_name;//新的分类名字
                        formData.isUpdateName = '1'; //是否修改了分类名字(0,不是 1,是)
                    }


                    if (formData.file_name) {
                        this.setState({
                            editConfirmLoading: true
                        });

                        formData.type_sequence = values.type_sequence + '';
                        app.post(type.UPDATE_TYPE, formData).then(req => {
                            this.setState({
                                editConfirmLoading: false
                            })
                            if (req.code == 1) {
                                this.setState({modal2Visible: false, file: [], fileList: []});
                                this.props.clickOk(formData);
                                app.alert('修改成功', 'info', 3);
                            } else {
                                app.alert(req.msg, 'error', 3);
                            }
                        })
                    }

                    else {
                        message.info('请上传图片');
                    }
                }
            });
        } else {
            message.info('请上传图片');
        }


    }

    setModal2Visible(modal2Visible, e) {
        let that = this;
        let xxx = this.props.myFileList;
        if (modal2Visible == true) {
            let formList = [];
            let formData = this.props.data;
            console.log(formData);
            const file_path=formData.file_path;
            const file_name=formData.file_name;
            const pictureList=[file_path];
            const item={
                file_path:file_path,
                file_name:file_name
            };
            const pictureList1=[item];
            formList['type_name'] = {value: formData.type_name};
            formList['type_sequence'] = {value: formData.type_sequence};
            this.props.form.setFields(formList);
            this.setState({
                pictureList,
                pictureList1
            })
        }
        this.setState({modal2Visible});
    }

    /**
     * 获取图片
     * @param intelligence
     * @param intelligence1
     */
    handleGetIntelligenceList(pictureList, pictureList1) {
        this.setState({pictureList, pictureList1});
    }
}

TypeEdit.propTypes = {}
const TypeEdits = Form.create()(TypeEdit);
const TypeManageForm = Form.create()(TypeManage);
export default TypeManageForm;